﻿using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace MovingBlocks.Classes
{
    /* Class for generating the blocks from bitmap */
    class PhotoBlocksGenerator
    {
        private int numberOfImageCols;
        private int numberOfImageRows;
        BitmapImage processedPhoto;
        WriteableBitmap photoAfterConvertion;
        List<WriteableBitmap> photoBlockList;

        private int picturePixelWidth;
        private int picturePixelHeight;

        public int rowsSize;
        public int colsSize;

        /* Constructor */
        public PhotoBlocksGenerator(int inputNumberOfCols, int inputNumberOfRows)
        {
            numberOfImageCols = inputNumberOfCols;
            numberOfImageRows = inputNumberOfRows;
            processedPhoto = InputArgumentsContext.Current.Image;
            photoBlockList = new List<WriteableBitmap>();
            picturePixelHeight= processedPhoto.PixelHeight;
            picturePixelWidth = processedPhoto.PixelWidth;
            rowsSize = picturePixelWidth / numberOfImageRows;
            colsSize = picturePixelHeight / numberOfImageCols;
        }

        /* Conversion of picked image to writable bitmap */
        private WriteableBitmap BitmapImageToWritableConvertion(BitmapImage photo)
        {
            //BitmapImage bitmapImage = new BitmapImage(new Uri("arka_projects_as_logo.png", UriKind.Relative));
            Image uiElement = new Image() { Source = photo };
            ScaleTransform t = new ScaleTransform() { ScaleX = 1, ScaleY = 1 };
            photoAfterConvertion = new WriteableBitmap(uiElement, t);

            return photoAfterConvertion;
        }

        /* Filling the list of cropped writable bitmaps */
        public List<WriteableBitmap> GeneratePhotoList()
        {
            int startPixelRow, startPixelCol;
            WriteableBitmap photoAfterConvertionPart;

            startPixelRow = 0;
            startPixelCol = 0;
            
            photoAfterConvertion = BitmapImageToWritableConvertion(processedPhoto);

            for (int i = 0; i < numberOfImageRows; i++)
            {
                for (int j = 0; j < numberOfImageCols; j++)
                {
                    photoAfterConvertionPart = photoAfterConvertion.Crop(startPixelRow, startPixelCol, rowsSize, colsSize);
                    //photoAfterConvertionPart.SaveToMediaLibrary("img" + j + i, false);
                    photoBlockList.Add(photoAfterConvertionPart);

                    startPixelCol = startPixelCol + colsSize;
                }
                startPixelCol = 0;
                startPixelRow = startPixelRow + rowsSize;
            }

                return photoBlockList;
        }
      
    }
}
